<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter, useRoute, type RouteRecordRaw } from 'vue-router'
import { useBreakpoint } from '@/hooks/useBreakpoint'
import { routes as topLevelRoutes } from '@/router/routes'
import { useUserStore } from '@/stores/user'
import { hasAccess } from '@/utils/accessUtil'
const { breakpoint, isMobile } = useBreakpoint()
const userStore = useUserStore()
const router = useRouter()

// 计算菜单模式：移动端为垂直模式，其他为水平模式
const menuMode = computed(() => (isMobile() ? 'vertical' : 'horizontal'))

const route = useRoute()

// 找到布局路由的子路由用于菜单
const layoutRoute = topLevelRoutes.find(r => r.name === 'layout')
const menuRoutes = computed((): RouteRecordRaw[] => {
  if (layoutRoute && layoutRoute.children) {
    return layoutRoute.children.filter(item => {
      if (item.meta?.hidden) {
        return false
      }
      if (item.meta?.access) {
        // console.log('item.meta?.access', item.meta?.access) // 保留 console.log 以便调试
        return hasAccess(userStore.userInfo, item.meta?.access)
      }
      return true
    })
  }
  return [] // 如果没有找到布局路由或子路由，返回空数组
})

// 使用计算属性来跟踪当前路由路径，确保刷新页面后也能保持当前菜单激活状态
const selectedKeys = computed(() => [route.path])
const handleSelect = (key: string) => {
  router.push({ path: key })
}

// 跳转到登录页
const goToLogin = () => {
  router.push('/login')
}

// 退出登录
const logout = () => {
  console.log('退出登录');
  userStore.logout()
}

// 跳转到个人资料页
const getToUserInfo = () => {
  router.push('/user/info')
}
</script>

<template>
  <a-row class="global-header" align="center" :wrap="false">
    <a-col class="logo-container">
      <!-- Logo移出菜单，放在导航前面 -->
      <router-link to="/" class="logo-link">
        <img src="@assets/images/logo-new.png" alt="Sakura OJ" class="logo-image" />
      </router-link>
    </a-col>
    <a-col flex="auto">
      <!-- 桌面端导航 -->
      <div class="desktop-menu">
        <a-menu
          :mode="menuMode"
          :breakpoint="breakpoint"
          :selected-keys="selectedKeys"
          @menu-item-click="handleSelect"
        >
          <a-menu-item
            v-for="item in menuRoutes"
            :key="
              layoutRoute.path === '/' && item.path === ''
                ? '/'
                : layoutRoute.path.replace(/\/$/, '') + '/' + item.path.replace(/^\//, '')
            "
          >
            {{ item.meta?.title }}
          </a-menu-item>
        </a-menu>
      </div>
    </a-col>
    <a-col flex="100px">
      <div class="user-info">
        <template v-if="userStore.userInfo">
          <a-dropdown trigger="hover">
            <a-avatar class="avatar" :imageUrl="userStore.userInfo?.userAvatar" @click="getToUserInfo()"></a-avatar>
            <template #content>
              <a-doption @click="() => Message.info('账号设置功能正在开发中~')">账号设置</a-doption>
              <a-doption @click="logout()">退出登录</a-doption>
            </template>
          </a-dropdown>
        </template>
        <a-button v-else type="primary" size="small" @click="goToLogin"> 登录 </a-button>
      </div>
    </a-col>
  </a-row>
</template>

<style scoped>
.global-header {
  /* width: 100%; */ /* Replaced by max-width and auto margins for centering */
  max-width: 1200px; /* Default max-width, matches content-wrapper */
  margin-left: auto;
  margin-right: auto;
  height: 100%;
}

.logo-container {
  display: flex;
  align-items: center;
  height: 100%;
  width:max-content;
  flex: none;
}

.logo-link {
  display: flex;
  align-items: center;
  text-decoration: none;
}

.logo-image {
  height: 36px;
  width: auto;
  object-fit: contain;
  transition: all 0.3s ease;
}

.user-info {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  height: 100%;
  font-weight: 500;
  color: var(--color-text-1);
  /* The user's local change for padding-right: 15px will apply here */
}

.user-info .avatar {
  /* 变成小手 */
  cursor: pointer;
}

/* 响应式调整 - 保持与 BasicLayout.vue content-wrapper 一致 */
@media (max-width: 576px) {
  .global-header {
    /* On very small screens, BasicLayout's content-wrapper padding is 8px. */
    /* Header might want to revert to full width with padding or match this. */
    /* For now, keeping max-width behavior. If full width with padding is desired: */
    /* max-width: none; padding: 0 10px; */
    /* However, logo/menu/user-info might need specific handling then. */
    /* Sticking to max-width alignment principle. */
    padding: 0 10px; /* Match BasicLayout content padding at this size if not using max-width logic */
    /* Or, if still using max-width, ensure it looks good. */
    /* Let's assume for xs, it's better to use padding for spacing from screen edges */
    max-width: none; /* Revert to full width with padding for very small screens */
  }
  .logo-image {
    height: 28px;
  }
}

/* 平板设备及中等屏幕 - sm, md, lg */
@media (min-width: 576px) and (max-width: 768px) {
  /* BasicLayout.vue .content-wrapper is max-width: 100% (effectively full with parent padding) */
  /* BasicLayout.vue .content has padding: 12px */
  .global-header {
    max-width: none; /* Full width like content-wrapper */
    padding: 0 12px; /* Match parent content padding */
  }
}

@media (min-width: 768px) and (max-width: 1200px) {
  .global-header {
    max-width: 960px; /* Matches content-wrapper */
    padding: 0; /* Reset padding when max-width is active */
  }
  .logo-image {
    height: 32px;
  }
}

@media (min-width: 1200px) {
  /* This is the default state for .global-header above (max-width: 1200px, no padding) */
  /* Explicitly setting padding:0 here in case of cascading from smaller breakpoints */
  .global-header {
    padding: 0;
  }
  .logo-image {
    height: 36px;
  }
}
</style>
